package smlab.loader
{
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.utils.ByteArray;
	
	[Event(name="complete",type="flash.events.Event")]
	[Event(name="error",type="flash.events.ErrorEvent")]

	/**
	 * URLStream 升级版
	 * @author simon
	 * 
	 */
	public class URLStream_SM extends EventDispatcher
	{
		private var _urlStream:URLStream;
		private var _bytes:ByteArray;
		
		public function URLStream_SM(target:IEventDispatcher=null)
		{
			super(target);
			_urlStream=new URLStream;
		}
		
		private function configureListeners(d:EventDispatcher,remove:Boolean=false):void
		{
			if(!d)return;
			if(remove){
				d.removeEventListener(Event.COMPLETE, completeHandler);
	            d.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
	            d.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
	            d.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
			}else{
				d.addEventListener(Event.COMPLETE, completeHandler);
	            d.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
	            d.addEventListener(ProgressEvent.PROGRESS, progressHandler);
	            d.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
			}
           
        }
        
        public function load(url:String):void
        {
        	configureListeners(_urlStream);
        	_urlStream.load(new URLRequest(url));
        }
        
        public function get bytes():ByteArray
        {
        	return _bytes;
        }
        
        private function completeHandler(e:Event):void 
        {
        	_bytes=new ByteArray;
			
			if(_urlStream.bytesAvailable>0)
			{
				_urlStream.readBytes(_bytes);
				dispatchEvent(new Event(Event.COMPLETE));
			}else{
				errorHandler(null);
				return;
			}
			_urlStream.close();
			configureListeners(_urlStream,true);
        }
        
        private function errorHandler(e:*):void
		{
			dispatchEvent(new ErrorEvent(ErrorEvent.ERROR));
		}
		
		private function progressHandler(e:ProgressEvent):void
		{
			dispatchEvent(e);
		}
	}
}